function adhocGetProfileName() {
  var DirectoryService = Components.classes["@mozilla.org/file/directory_service;1"].
                           getService(Components.interfaces.nsIProperties);
  var path = DirectoryService.get("ProfD", Ci.nsIFile).path;
  var arr = path.split(".");
  return arr[arr.length - 1];
}

//TODO integrate with a same function at schema.js
function parseLocationHref(aURISpec) {
  var m = null;
  var reXmppSlashSlashUserSendto = /^xmpp:\/\/([^\/\?#]+)\/([^\/\?#]+)/;
  m = reXmppSlashSlashUserSendto.exec(aURISpec);
  var user   = "";
  var sendto = "";
  var url    = "http://www.yahoo.co.jp/";
  if (m) {
    user   = m[1];
    sendto = m[2];
  } else {
    var reXmppColon = /^xmpp:([^\/\?#]+)/;
    m = reXmppColon.exec(aURISpec);
    if (m) {
      switch (adhocGetProfileName()) {
      case "xmppweb":
        user = "romeo@localhost";
        break;
      case "xmppweb2":
        user = "juliet@localhost";
        break;
      default:
        user = "default@localhost";
        break;
      }
      sendto = m[1];
    }
  }
  m = /href;url=(.*)$/.exec(aURISpec);
  if (m) url = m[1];
  return [user, sendto, url];
}

function handleMusubiCommand(aTriggeringEvent) {
  if (!gURLBar) return;
  var musubiUserBar   = document.getElementById("musubi-userbar");
  var musubiSendtoBar = document.getElementById("musubi-sendtobar");
  var musubiURLBar    = document.getElementById("musubi-urlbar");
  if (!musubiURLBar.value || !musubiSendtoBar.value) return;
  if (musubiUserBar.value) {
    gURLBar.value = "xmpp://" +
                    musubiUserBar.value +
                    "/" +
                    musubiSendtoBar.value +
                    "?href;url=" +
                    musubiURLBar.value;
  } else {
    gURLBar.value = "xmpp:" +
                    musubiSendtoBar.value +
                    "?href;url=" +
                    musubiURLBar.value;
  }
  handleURLBarCommand(aTriggeringEvent);
}

function browserOnLoad(aEvent) {
  var musubiUserBar   = document.getElementById("musubi-userbar");
  switch (adhocGetProfileName()) {
  case "xmppweb":
    musubiUserBar.value = "romeo@localhost";
    break;
  case "xmppweb2":
    musubiUserBar.value = "juliet@localhost";
    break;
  }
  gBrowser.tabContainer.addEventListener("TabSelect", onTabSelected, false);
}

function browserOnUnload(aEvent) {
  gBrowser.tabContainer.removeEventListener("TabSelect", onTabSelected, false);
}

function onTabSelected(aEvent) {
  var [user,sendto,url] = parseLocationHref(gBrowser.selectedTab.linkedBrowser.contentWindow.document.location.href);
  document.getElementById("musubi-userbar")  .value = user;
  document.getElementById("musubi-sendtobar").value = sendto;
  document.getElementById("musubi-urlbar")   .value = url;
}

getBrowser().addEventListener("load",   browserOnLoad,   true);
getBrowser().addEventListener("unload", browserOnUnload, true);